/**
 * ProductController
 *
 * @description :: Server-side logic for managing products
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
	getProducts: function (req, res) {
	  if (req.param('categoryId')) {
	    Product.find({category: req.param('categoryId')}).then(function (record) {
        console.log('get by cat');
        res.send(record)
      })
    } else {
      Product.find().then(function (record) {
        console.log('get products');
        res.send(record);
      }).catch(function (err) {
        console.log(err);
      })
    }
  },

  getProduct: function (req, res) {
    var id = req.params.id;
    Product.find({id: id}).then(function (record) {
      console.log('get product:', record);
      res.send(record);
    }).catch(function (err) {
      console.log(err)
    })
  },

  createProduct: function (req, res) {
    var json = req.body;
    Product.create(json).then(function (created) {
      console.log('create new product:', created);
      res.ok('ok');
    })
  },

  updateProduct: function (req, res) {
    var id = req.params.id;
    var json = req.body;
    Product.update({id: id}, json).then(function (updated) {
      console.log('update product:', updated);
      res.ok('ok')
    }).catch(function (err) {
      console.log(err);
    })
  },

  deleteProduct: function (req, res) {
    var p_id = req.params.id;
    console.log(p_id);
    Product.destroy({id: p_id}).exec(function (err) {
      if (err) console.log(err)
      console.log('delete product')
      res.ok('ok');
    })
  },

  getCategories: function (req, res) {
    Category.find().then(function (record) {
      console.log('get categories');
      res.send(record);
    }).catch(function (err) {
      console.log(err);
    })
  },

  createCategory: function (req, res) {
	  var json = req.body;
    Category.create(json).then(function (created) {
      console.log('create new category:', created);
      res.ok('ok');
    }).catch(function (err) {
      console.log(err);
    })
  }
};

